// pages/pay/pay.js
const SERVICE = require("../../service.js");

Page({

  /**
   * 页面的初始数据
   */
  data: {

  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    console.log(options);
    let _this = this;
    _this.setData({
      remark: options.remark ? options.remark : ''
    });
    let openid = wx.getStorageSync("token");    
    if (options.type && options.type === "1") {
      SERVICE.unpaid({ openid, order_id: options.orderId }, (status, data) => {
        console.log("结算数据 type = 1：",data);
        if(status){
          _this.setData({
            payInfo: data.data
          });
        }
      });
    } else {
      let orderData = JSON.parse(options.orderData);
      let arry = [];
      for (let i = 0; i < orderData.goods.length; i++) {
        arry.push(orderData.goods[i].rec_id);
      }
      console.log("结算页面options:", orderData);
      console.log("备注：",options.remark);
      wx.showNavigationBarLoading();
      SERVICE.pay({
        shipping: orderData.shipping.id,  //快递方式ID
        payment: orderData.payment.id,   //支付方式ID
        surplus: 0,
        postscript:options.remark,   //留言
        vehicle: arry,   //购买的商品ID,单个为int类型，多个为array类型
        step: "done",
        express_time: options.date,
        openid
      }, (status, data) => {
        wx.hideNavigationBarLoading();
        console.log("结算数据：", data);
        
        if (status) {
          _this.setData({
            payInfo: data.data
            
          });
        }
      });
    }

  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  },
  pay() {
    let td = this.data,payData = JSON.parse(td.payInfo.button.jsApiParameters);
    wx.requestPayment({
      timeStamp: payData.timeStamp,
      nonceStr: payData.nonceStr,
      package: payData.package,
      signType: payData.signType,
      paySign: payData.paySign,
      success: function (res) {
        wx.showToast({
          title: "支付成功",
          icon: "none",
          mask: true
        });
        setTimeout(() => {
          wx.switchTab({
            url: '../my-center/my-center',
          });
        }, 1500);
        
      },
      fail: function (res) {
        console.log(res);
        if (res.errMsg == "requestPayment:fail cancel"){
          wx.showToast({
            title: "取消支付",
            icon:"none",
            mask:true
          });
        }
      }
    })
  }
})